package com.example.parse_springboot.controller;

import com.example.parse_springboot.entity.LiteflowChain;
import com.example.parse_springboot.entity.MyContext;
import com.example.parse_springboot.entity.Result;
import com.example.parse_springboot.entity.RunParam;
import com.example.parse_springboot.mapper.ChainMapper;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.flow.LiteflowResponse;
import com.yomahub.liteflow.slot.DefaultContext;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/chain")
public class ChainController {
    @Autowired
    private ChainMapper mapper;

    @Resource
    private FlowExecutor flowExecutor;

    @PostMapping("/run")
    public Result<Map<String, Object>> execute(@RequestBody RunParam param) {
        int insert = mapper.insert(param.getChain());
        if (insert <= 0) {
            return new Result<Map<String, Object>>(0);
        }
        flowExecutor.reloadRule();
        String name = param.getChain().getChainName();

        LiteflowResponse response = flowExecutor.execute2Resp(name, param.getData(), MyContext.class);

        if (response.isSuccess()) {
            MyContext contextBean = response.getContextBean(MyContext.class);
            Map<String, Object> map = new HashMap<>();
            map.put("step", response.getExecuteStepStr());
            map.put("context", contextBean.getDataMap());
            return Result.success(map);
        } else {
            return new Result<Map<String, Object>>(0);
        }
    }
}
